package com.zlp.netty.nio;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static com.zlp.netty.buffer.ByteBufferUtil.debugAll;
import static com.zlp.netty.buffer.ByteBufferUtil.debugRead;

/**
 * @author: zhulaiping
 * @time: 2022/8/24 14:21
 */
@Slf4j
public class NIOServerDemo4Worker {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        Worker[] worker = new Worker[4];
        AtomicInteger robin = new AtomicInteger(0);
        for (int i=0;i<worker.length;i++){
            worker[i] = new Worker("work-"+i);
        }
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                log.debug("thread:{},key:{}",Thread.currentThread().getName(),key);
                iterator.remove();;
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    worker[robin.getAndIncrement()%worker.length].register(socketChannel);
                }
            }
        }
    }

    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        private String name;
        private boolean start = false;

        public Worker(String name){
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if(!start){
                selector = Selector.open();
                thread = new Thread(this,name);
                thread.start();
                start = true;
            }
            queue.add(()->{
                try {
                    sc.register(selector,SelectionKey.OP_READ);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            //相当于信号量，先于select()执行，或后于select()执行对结果均无影响
            selector.wakeup();

        }


        @Override
        public void run() {
            while (true){
                    try {
                        selector.select();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    Runnable task = queue.poll();
                    if(task!=null){
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        log.debug("thread:{},key:{}",Thread.currentThread().getName(),key);
                        iterator.remove();
                        if(key.isReadable()){
                            try {
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                int read = channel.read(buffer);
                                if(read == -1){
                                    key.cancel();
                                }
                                debugAll(buffer);
                            }catch (Exception e){
                                e.printStackTrace();
                                key.cancel();
                            }

                        }
                    }
            }

        }
    }

}
